package game.level;

import java.io.*; 

import engine.game.Game;
import engine.game.Level;
import engine.objects.ObjectInspector;

public class LevelSaveLoad {

	private static final String filePath = "res/saves/level.ser" ; 
	
	public void save(Level l){
		ObjectOutputStream oos = null ; 
		try{
			oos = new ObjectOutputStream(new FileOutputStream(filePath));
			oos.writeObject(l); 
		}catch(Exception e){
			System.out.println("Fehler beim Speichern des Levels!");
			e.printStackTrace(); 
		}finally{
			try {
				oos.close();
				System.out.println("Spielstand wurde erfolgreich gespeichert unter "+filePath);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public Level load(Game g){
		ObjectInputStream ois = null ; 
		TestLevel result = null ; 
		try{
			ois = new ObjectInputStream(new FileInputStream(filePath)); 
			Object o = ois.readObject(); 
			if(ObjectInspector.isInstance(o, Level.class)){
				Level l = (Level)ObjectInspector.getInstance(o, Level.class);
				l.initGame(g);
				if(ObjectInspector.isInstance(l, TestLevel.class))
					result = (TestLevel) ObjectInspector.getInstance(l, TestLevel.class);
			}
		}catch(Exception e){
			System.out.println("Fehler beim Laden des Levels!");
		}finally{
			try {
				ois.close();
				System.out.println("Das Level aus der Speicherdatei "+filePath+" wurde erfolgreich geladen :)");
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
		return result ; 
	}
	
}
